<template>
  <div>
    <div class="components_edit_modal questionnaire-edit">
    <el-dialog title="发起调查问卷" width="1000px" :visible.sync="state" @open="open" :show-close="true" :close-on-click-modal="false">
      <el-form :model="questionnaireParams" :rules="rules" ref="questionnaireParams" label-position="right"
               :close-on-click-modal="false">

        <el-form-item label="调查问卷" prop="questionnaireId" class="lineblock">
          <el-select v-model="questionnaireParams.questionnaireId" placeholder="请选择调查问卷">
            <el-option v-for="school in questionnaireList" :label="school.questionnaireName" :value="school.id"
                       :key="school.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择时间" prop="beginTime" class="lineblock">
          <el-date-picker
            v-model="timeRange"
            @change="timeChange"
            format="yyyy-MM-dd HH:mm"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>


        <el-form-item label="选择被调查人" prop="questionnaireVOS">
          <el-button type="primary" size="mini" @click="showUser()">选择</el-button>
        </el-form-item>
        <el-form-item class="lineblock" label="被调查人" v-if="teacherClassCourseList.length > 0">
          <el-table :data="teacherClassCourseList"
                    border stripe style="width: 100%" class="components_edit_tables">
            <el-table-column prop="teacherName" label="被调查人" align="center" width="90">
            </el-table-column>
            <el-table-column prop="resourceRequirement" label="所负责班级" align="center" width="470">
              <template slot-scope="scope">
                <el-select v-model='teacherClassCourseIds[scope.$index].idList'   multiple collapse-tags placeholder='不选默认为全部班级'>
                  <el-option v-for='item in teacherClassCourseList[scope.$index].list' :key='item.labelId' :label='item.label'
                             :value='item.labelId'></el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column prop="substituteTeacherName" label="代课老师" align="center" width="100">
              <template slot-scope="scope">
                <el-popover trigger="click" placement="top" width="600"  >
                  <el-form  label-position="right" :inline="true" size="small">
                    <template v-if="teacherClassCourseList[scope.$index].list && teacherClassCourseList[scope.$index].list.length > 0"
                              v-for="(item,k) in teacherClassCourseList[scope.$index].list">

                      <el-form-item  v-for="(idItem,key) in teacherClassCourseIds[scope.$index].idList" :key="key"  v-if="idItem == item.labelId"
                                      :label="teacherClassCourseList[scope.$index].list[k].label">
                        <el-input placeholder="代课老师" v-model="teacherClassCourseList[scope.$index].list[k].substituteTeacherName"></el-input>
                      </el-form-item>
                    </template>
                    <template v-else>
                      <span>请先选择中所负责班级</span>
                    </template>
                  </el-form>
                  <div slot="reference" class="name-wrapper">
                    <el-button size="mini">设置</el-button>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="supportContent" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="teacherDel(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="备注" prop="remark" class="lineblock textareaBox">
          <el-input v-model.trim="questionnaireParams.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="addQuestionnaire('questionnaireParams')">确 定</el-button>
        <el-button size="mini" @click="state = false">关 闭</el-button>
      </div>

    </el-dialog>

    </div>
    <select-teacher-component ref="selectTeacherComponent"></select-teacher-component>
  </div>

</template>

<script>
  import {enums} from '@/constant'
  import select_teacher_component from './select-teacher-component'

  export default {
    components: {
      "select-teacher-component": select_teacher_component
    },
    data() {
      var checkList = (rule, value, callback) => {
        if (this.teacherClassCourseList && this.teacherClassCourseList.length > 0) {
          callback();
        }else{
          callback(new Error('被调查人不能为空'));
        }
      };
      return {
        state: false,
        timeRange:[],
        rules: {
          questionnaireId: [
            {required: true, message: '调查问卷不能为空', trigger: 'change', type: "number"},
          ],
          beginTime: [
            {required: true, message: '请选择时间',},
          ],
          questionnaireVOS:[
            {validator:checkList},
          ]
        },
        questionnaireParams: {
          id:null,
          questionnaireId: null,
          beginTime: null,
          endTime: null,
          remark: null,
          questionnaireVOS: []
        },
        //教师班级信息集合
        teacherClassCourseList:[],
        //教师班级id集合
        teacherClassCourseIds:[],
        questionnaireList: [],
      }
    },
    created() {

    },
    mounted() {
    },
    methods: {
      timeChange(val){
        this.questionnaireParams.beginTime = val[0];
        this.questionnaireParams.endTime = val[1];
      },
      showUser() {
        this.$refs.selectTeacherComponent.showDialog();
      },
      //被调查人弹窗 回调函数
      callBackTeachers(resultData) {
        let self = this;
        let questionnaireVOS = self.teacherClassCourseList.concat(resultData);
        let hash = {};
        //去重
        self.teacherClassCourseList = questionnaireVOS.reduce(function (item, next) {
          hash[next.teacherId] ? '' : hash[next.teacherId] = true && item.push(next);
          return item
        }, []);
        this.teacherClassCourseIds = [];
        for(let i =0;i<self.teacherClassCourseList.length;i++){
          this.teacherClassCourseIds.push({teacherId:self.teacherClassCourseList[i].teacherId,teacherName:self.teacherClassCourseList[i].teacherName,idList:[]});
          //初始化负责班级课程集合
          this.$set(this.teacherClassCourseList[i],'list',[]);
          this.initTeacherSourses(i,self.teacherClassCourseList[i].teacherId);
        }
      },
      initTeacherSourses(index,teacherId,idList,subTeachers){
        let vm = this;
          vm.axios.get(api.questionnaire.classListByTeacherId, {params: {teacherId:teacherId}})
            .then((response) => {
              let result = response.data;
              if (result.success) {
                if(result.data.list){
                  let tempList = result.data.list;

                  for(let i =0;i<tempList.length;i++){
                    tempList[i].label = tempList[i].schoolName+"/"+tempList[i].professionName+"/"
                      +tempList[i].className+"/"+tempList[i].courseName;
                    let labelId = tempList[i].classId+"-"+tempList[i].courseNo;
                    tempList[i].labelId = labelId;
                    if(subTeachers){
                      tempList[i].substituteTeacherName = subTeachers[labelId];
                    }
                  }
                  vm.$set(vm.teacherClassCourseList[index],'list',tempList);
                  if(idList){
                    vm.$set(vm.teacherClassCourseIds[index],'idList',idList);
                  }
                }
              } else {
                vm.$message.error(response.data.msg);
              }
            })
      },
      // 新建调查问卷
      addQuestionnaire(questionnaireParams) {
        let self = this;
        this.$refs['questionnaireParams'].validate((valid) => {
          if (valid) {
            let url = api.questionnaire.initiateQuestionnaire;
            let questionnaireParams = self.getQuestionnaireParams();
            this.axios.post(url, questionnaireParams)
              .then((response) => {
                if (response.data.success) {
                  self.$message({
                    type: 'success',
                    message: response.data.msg,
                  });
                  self.$parent.$refs.questionnaireTable.$emit('vuetable:refresh');
                  self.state = false;
                } else {
                  self.$message.error(response.data.msg);
                }
              })
          } else {
            return false;
          }
        });
      },
      getQuestionnaireParams() {
        if(this.teacherClassCourseIds && this.teacherClassCourseIds.length > 0){
          let tempList = [];
          for(let i =0;i<this.teacherClassCourseIds.length;i++){
            let idList = this.teacherClassCourseIds[i].idList;

            if(idList && idList.length > 0){
              //自选班级的情况
              for(let j = 0;j< idList.length;j++){
                if(this.teacherClassCourseList[i].list){
                  this.teacherClassCourseList[i].list.forEach((item)=>{
                    if(item.labelId == idList[j]){
                      tempList.push(item);
                    }
                  });
                }
              }
            }else{
              //未选班级的情况,后台通过判断为空的字段自己处理
              let item = {
                teacherId:this.teacherClassCourseIds[i].teacherId,
                teacherName:this.teacherClassCourseIds[i].teacherName,
              };
              tempList.push(item);
            }
          }
          this.questionnaireParams.questionnaireVOS = tempList;
        }
        let questionnaireParams = this.questionnaireParams;
        for (let i = 0; i < this.questionnaireList.length; i++) {
          if (this.questionnaireList[i].id == questionnaireParams.questionnaireId) {
            questionnaireParams.questionnaireName = this.questionnaireList[i].questionnaireName;
          }
        }
        return questionnaireParams;
      },
      showDialog(id) {
        this.state = true;
        if (id) {
          this.questionnaireParams.id = id;
        }else{
          this.questionnaireParams.id = null;
        }
      },
      open(){
        let self = this;
        this.$nextTick(()=>{
          //清空验证
          self.$refs['questionnaireParams'].resetFields();
          //清空初始数据
          self.clear();
          //初始化调查问券列表
          self.getQuestionnaireList();
          //回显数据
          if(self.questionnaireParams.id){
            self.initData(()=>{
              self.timeRange.push(self.questionnaireParams.beginTime);
              self.timeRange.push(self.questionnaireParams.endTime);
              let hash = {};
              //去重
              let teacherList = self.questionnaireParams.questionnaireVOS.reduce(function (item, next) {
                hash[next.teacherId] ? '' : hash[next.teacherId] = true && item.push(next);
                return item
              }, []);
              let voList = self.questionnaireParams.questionnaireVOS;
              for(let i = 0;i<teacherList.length;i++){
                //之前选中的课程
                let idList = [];
                //代课老师名称集合
                let subTeachers = {};

                  for(let j = 0;j<voList.length;j++){
                  if(voList[j].teacherId == teacherList[i].teacherId) {
                    let labelId = voList[j].classId + "-" + voList[j].courseNo;
                    idList.push(labelId);
                    subTeachers[labelId] = voList[j].substituteTeacherName;
                  }
                }
                self.teacherClassCourseList.push(teacherList[i]);
                self.teacherClassCourseIds.push(teacherList[i]);
                self.initTeacherSourses(i,teacherList[i].teacherId,idList,subTeachers);
              }
            });
          }
        });
      },
      initData(callback){
        let self = this;
        self.axios.get(api.questionnaire.questionnaireDetail.replace("{id}",self.questionnaireParams.id))
          .then((response) => {
          if (response.data.success) {
            let result = response.data.data;
            for (let attr in result) {
              self.questionnaireParams[attr] = result[attr];
            }
            //后续处理
            callback();
          } else {
            self.$message.error(response.data.msg);
          }
        })
      },
      clear(){
        for(let attr in this.questionnaireParams){
          if(attr == 'id'){
              continue;
          }
          if(attr == 'questionnaireVOS'){
            this.questionnaireParams[attr] = [];
          }else{
            this.questionnaireParams[attr] = null;
          }
        }
        this.teacherClassCourseList = [];
        this.teacherClassCourseIds = [];
        this.questionnaireList = [];
        this.timeRange = [];
      },
      teacherDel(index){
        this.questionnaireParams.questionnaireVOS.splice(index,1);
        this.teacherClassCourseList.splice(index,1);
        this.teacherClassCourseIds.splice(index,1);
      },
      getQuestionnaireList() {
        let self = this;
        self.axios.get(api.questionnaire.queryQuestionnaireList).then((response) => {
          if (response.data.success) {
            self.questionnaireList = response.data.data;
          } else {
            self.$message.error(response.data.msg);
          }
        })
      }
    }
  };
</script>
<style>
.questionnaire-edit .el-table__body-wrapper{
  overflow: hidden;
}
.questionnaire-edit .el-date-editor .el-range-input,
.questionnaire-edit .el-date-editor .el-range-separator{
  margin: -5px 0 0 0;
}

.questionnaire-edit .el-date-editor .el-range__close-icon,
.questionnaire-edit .el-date-editor .el-range__icon{
  line-height: 22px;
}
</style>
